package com.cskaoyan.service.impl;

import com.cskaoyan.bean.PageData;
import com.cskaoyan.bean.PageParameter;
import com.cskaoyan.mapper.MarketStorageMapper;
import com.cskaoyan.model.MarketStorage;
import com.cskaoyan.model.MarketStorageExample;
import com.cskaoyan.service.StorageService;
import com.cskaoyan.utils.MyBatisUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * @Author Pudding
 * @Date 2024/5/30 15:27
 */
public class StorageServiceImpl implements StorageService {
    @Override
    public PageData list(PageParameter pageParameter, String key, String name) {
        //1. 通过请求参数和mybatis进行数据的分页+条件查询
        //1.1 开启分页：通过分页插件进行分页
        PageHelper.startPage(pageParameter.getPage(), pageParameter.getLimit());
        //1.2 通过example类构造条件：做排序：sort、order
        MarketStorageExample example = new MarketStorageExample();
        example.setOrderByClause(pageParameter.getSort() + " " + pageParameter.getOrder());
        //1.3 继续增加条件
        MarketStorageExample.Criteria criteria = example.createCriteria();
        if (key != null && !"".equals(key)) {
            criteria.andKeyEqualTo(key);
        }
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        //1.4 继续增加条件，没有被逻辑删除的
        criteria.andDeletedEqualTo(false);

        //2. 通过mybatis进行查询数据
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketStorageMapper storageMapper = sqlSession.getMapper(MarketStorageMapper.class);
        //2.1 把example封装的对象传入进行
        List<MarketStorage> marketStorages = storageMapper.selectByExample(example);
        //2.2 将查询的数据，也就是data中的list封装到data中
        PageData pageData = PageData.list(marketStorages);
        //2.3 返回响应报文中的data数据即可
        return pageData;
    }

    @Override
    public void update(MarketStorage marketStorage) {
        //根据请求体中的参数封装的对象来修改数据库表中的数据
        //1. 使用mybatis来更新数据
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketStorageMapper storageMapper = sqlSession.getMapper(MarketStorageMapper.class);
        storageMapper.updateByPrimaryKeySelective(marketStorage);

        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void delete(MarketStorage marketStorage) {
        //根据请求体中的参数封装的对象来删除数据库表中的数据
        //1. 使用mybatis来删除数据
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketStorageMapper storageMapper = sqlSession.getMapper(MarketStorageMapper.class);
        storageMapper.deleteByPrimaryKey(marketStorage.getId());

        sqlSession.commit();
        sqlSession.close();
    }

}
